package com.linjian.togetherbirthday.utils;

import com.google.gson.Gson;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by 27565 on 2018/4/8.
 */

public class HttpUtils {

    private static OkHttpClient client = null;

    private HttpUtils() {}

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (HttpUtils.class) {
                if (client == null)
                    client = new OkHttpClient();
            }
        }
        return client;
    }
//    public static Response doGetTwo(String url) {
//        Response response = null;
//        Request request = new Request.Builder()
//                .url(url)
//                .build();
////        Call call = getInstance().newCall(request);
////        call.enqueue(callback);
//        try {
//            response = getInstance().newCall(request).execute();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return response;
//    }
    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url,String cookie, Callback callback) {
        Request request = new Request.Builder()
                .addHeader("Cookie",cookie)
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    public static void doGetCode(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    /**
     * GET请求加请求
     *
     * @param url
     * @param callback
     */
//    public static void doGetTwo(String url, String o , Callback callback) {
//        String o1 = o.replace("\n","");
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("userId",o1)
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
    /**
     * GET请求加请求
     *
     * @param url
     * @param callback
     */
//    public static void doGetThree(String url, String o , Callback callback) {
//        String o1 = o.replace("\n","");
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("address",o1)
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
//    public static void doPost(String url,String cookie, Map<String, Object> mapParams, Callback callback) {
//        FormBody.Builder builder = new FormBody.Builder();
//        for (String key : mapParams.keySet()) {
//            builder.add(key, mapParams.get(key));
//        }
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("Cookie",cookie)
//                .post(builder.build())
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
    /**
     * Post请求发送键值对数据
     *加请求头
     * @param url
     * @param mapParams
     * @param callback
     */
//    public static void doPostT(String url, String head, Map<String, String> mapParams, Callback callback) {
//        String head1 = head.replace("\n","");
//        FormBody.Builder builder = new FormBody.Builder();
//        for (String key : mapParams.keySet()) {
//            builder.add(key, mapParams.get(key));
//        }
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("userId",head1)
//                .post(builder.build())
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
    /**
     * Post请求发送JSON数据
     *
     * @param url
     * @param jsonParams
     * @param callback
     */
//    public static void doPost(String url, String jsonParams, Callback callback) {
//        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
//                , jsonParams);
//        Request request = new Request.Builder()
//                .url(url)
//                .post(body)
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }

    /**
     * Post请求发送JSON数据
     *加请求头
     * @param url
     * @param jsonParams
     * @param callback
     */
//    public static void doPostT(String url, String head, String jsonParams, Callback callback) {
//        String head1 = head.replace("\n","");
//        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
//                , jsonParams);
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("userId",head1)
//                .post(body)
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
    /**
     * 上传文件
     *
     * @param url
     * @param pathName
     * @param fileName
     * @param callback
     */
    public static void doFile(String url,String cookie, String pathName, String fileName, Callback callback) {
        //判断文件类型
        MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
        //创建文件参数
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(MEDIA_TYPE, new File(pathName)));
        //发出请求参数
        Request request = new Request.Builder()
                .addHeader("Cookie",cookie)
                .header("Authorization", "Client-ID " + "...")
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * 根据文件路径判断MediaType
     *
     * @param path
     * @return
     */
    private static String judgeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 下载文件
     * @param url
     * @param fileDir
     * @param fileName
     */
//    public static void downFile(String url, final String fileDir, final String fileName) {
//        Request request = new Request.Builder()
//                .url(url)
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                InputStream is = null;
//                byte[] buf = new byte[2048];
//                int len = 0;
//                FileOutputStream fos = null;
//                try {
//                    is = response.body().byteStream();
//                    File file = new File(fileDir, fileName);
//                    fos = new FileOutputStream(file);
//                    while ((len = is.read(buf)) != -1) {
//                        fos.write(buf, 0, len);
//                    }
//                    fos.flush();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (is != null) is.close();
//                    if (fos != null) fos.close();
//                }
//            }
//        });
//    }


    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void Put(String url,String cookie,String head,String headData, Map<String, Object> mapParams, Callback callback) {

        Request request = new Request.Builder()
                .url(url)
                .header("Cookie",cookie)
                .addHeader(head,headData)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(mapParams)))
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

//    public static void PutOne(String url,String cookie, Map<String, Object> mapParams, Callback callback) {
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("Cookie",cookie)
//                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(mapParams)))
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }
//    public static void PutTwo(String url, String head, Object object, Callback callback) {
//        Request request = new Request.Builder()
//                .url(url)
//                .addHeader("userId",head)
//                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(object)))
//                .build();
//        Call call = getInstance().newCall(request);
//        call.enqueue(callback);
//    }

    /**
     * 登录专用
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void PutLogin(String url, Map<String, Object> mapParams, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(mapParams)))
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    public static void PutCookie(String url,String cookie, Map<String, Object> mapParams, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .header("Cookie",cookie)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(mapParams)))
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }


    public static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    /**
     * 上传多张图片及参数
//     * @param  URL地址
//     * @param params 参数
//     * @param pic_key 上传图片的关键字
//     * @param paths  图片路径
     */
    public static void doMoreFile(String url, String cookie, List<String> pathName,List<String> fileName, Callback callback) {
//        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        for (int i = 0; i < pathName.size(); i++) {
            //判断文件类型
            MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName.get(i)));
            //创建文件参数
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", fileName.get(i),
                            RequestBody.create(MEDIA_TYPE, new File(pathName.get(i))));
            //发出请求参数
            Request request = new Request.Builder()
                    .addHeader("Cookie", cookie)
                    .header("Authorization", "Client-ID " + "...")
                    .url(url)
                    .post(builder.build())
                    .build();
            Call call = getInstance().newCall(request);
            call.enqueue(callback);
        }
    }
}
